package com.yunban.project.api.text_check.service.impl;

import com.yunban.project.api.text_check.domain.CorrectionConfig;
import com.yunban.project.api.text_check.dto.GradioAiResp;
import com.yunban.project.api.text_check.service.AiCorrectionService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.base.common.exception.BusinessException;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

/**
 * @author: lijiajun
 * @date: 2024-11-22
 * @version: 1.0
 */
@Slf4j
@Service("gradioAiCorrectionService")
public class GradioAiCorrectionService implements AiCorrectionService {

    @Resource
    private RestTemplate restTemplate;

    @Override
    public String correction(String text, CorrectionConfig config, String taskId) {
        String url = config.getUrlPath();
        if (!StringUtils.hasText(url)) {
            throw new BusinessException(config.getName() + " 配置信息有误，请联系管理员~");
        }
        String params = "{\"text\":\"" + text + "\"}";
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        // 创建 HttpEntity 对象，包含请求体和请求头
        HttpEntity<String> req = new HttpEntity<>(params, headers);
        GradioAiResp result = restTemplate.postForObject(url, req, GradioAiResp.class);
        log.info("gradio text correction result:{}", result);
        if (ObjectUtils.isEmpty(result) || result.getCode() != 200) {
            log.error("gradio text correction result error:{}", result);
            return null;
        }
        // 发送post请求
        return result.getData();
    }
}
